package com.iframework.anson;

import java.util.List;

import com.google.gson.Gson;
import com.iframework.model.json.BookSource;
import com.iframework.model.json.BookSources;
import com.iframework.model.json.Books;
import com.iframework.model.json.Chapter.Chapter_List;
import com.iframework.tools.ApiUtil;
import com.iframework.tools.BaseTools;
import com.iframework.tools.DBHelp_JDBC_MySQL;
import com.iframework.tools.JSONUtil;

public class BookManager {
	private static int _type;

	/**
	 * @return type
	 */
	public static int getType() {
		return _type == 0 ? 1 : _type;
	}

	/**
	 * @param type
	 *            要设置的 type
	 */
	public static void setType(int type) {
		_type = type;
	}

	public static void BookManager(String rankingId, List<Books> bookList) {
		// 表名
		String tabName = "tbl_book";
		// 表字段
		String[] tab_fields = { "_id", "title", "categrouy", "author", "site", "cover", "shortIntro", "banned",
				"latelyFollower", "latelyFollowerBase", "retentionRatio", "minRetentionRatio", "RankingId", "created" };
		String[] u_fields = { "title", "categrouy", "author", "site", "cover", "shortIntro", "banned", "latelyFollower",
				"latelyFollowerBase", "retentionRatio", "minRetentionRatio", "RankingId", "updated" };
		String[] q_fields = { "_id" };
		String strNowTime = BaseTools.getNow();
		Books book;
		while (bookList.iterator().hasNext()) {
			book = bookList.get(0);
			String[] q_data = { book.get_id() };
			String[] q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data, q_fields);
			if (q_result == null) {
				bookList.remove(book);
				continue;
			}
			if (q_result.length == 1 && q_result[0] == null) {
				// BaseTools.log("新增书籍 "+book.getTitle());
				String[] data = { book.get_id(), book.getTitle(), book.getCat(), book.getAuthor(), book.getSite(),
						book.getCover(), book.getShortIntro(), String.valueOf(book.getBanned()),
						String.valueOf(book.getLatelyFollower()), String.valueOf(book.getLatelyFollowerBase()),
						book.getRetentionRatio(), String.valueOf(book.getMinRetentionRatio()), rankingId, strNowTime };
				DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,book.getTitle());
				
			} else {
				// BaseTools.log("更新书籍 "+book.getTitle());
				String[] u_data = { book.getTitle(), book.getCat(), book.getAuthor(), book.getSite(), book.getCover(),
						book.getShortIntro(), String.valueOf(book.getBanned()),
						String.valueOf(book.getLatelyFollower()), String.valueOf(book.getLatelyFollowerBase()),
						book.getRetentionRatio(), String.valueOf(book.getMinRetentionRatio()), rankingId, strNowTime };
				DBHelp_JDBC_MySQL.update(tabName, u_fields, u_data, q_fields, q_data,book.getTitle());
			}
			q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data, new String[] { "id" });
			BookSourceManager(q_result[0],book.get_id(),book.getTitle());
			// BaseTools.log("---->线程分隔符<----");
			bookList.remove(book);
		}
	}

	
	/**
	 * 书籍来源
	 * 
	 * @param bookId
	 *            本地Id
	 * @param _bookId
	 *            远程Id
	 * @author Anson
	 */
	public static void BookSourceManager(String bookId, String _bookId,String bookName) {
		Gson gson = new Gson();
		String sourcesJSON = toc(_bookId);
		if (!sourcesJSON.equals("")) {
			BookSources sources = gson.fromJson(sourcesJSON, BookSources.class);
			saveSources(bookId, sources,bookName);
			ChapterManager.getChapter(bookId, _bookId,bookName);
		}
	}

	

	/**
	 * 保存来源信息至数据库
	 * 
	 * @param _bookId
	 *            本地Id
	 * @param sources
	 *            Json对象
	 * @author Anson
	 */
	private static void saveSources(String bookId, BookSources sources,String bookName) {
		// 表名
		String tabName = "tbl_booksource";
		// 表字段
		String[] tab_fields = { "_id", "lastChapter", "link", "sourceName_EN", "sourceName_CN", "isCharge", "chaptersCount", "sourceStarting",
				"sourceHost", "bookID", "sourceType", "updated" };
		String[] u_fields = { "lastChapter", "link", "sourceName_EN", "sourceName_CN", "isCharge", "chaptersCount", "sourceStarting", "sourceHost",
				"bookID", "sourceType", "updated" };
		String[] q_fields = { "_id" };
		String strNowTime = BaseTools.getNow();
		BookSource source;
		while (sources.getBookSource().iterator().hasNext()) {
			source = sources.getBookSource().get(0);
			String[] q_data = { source.get_id() };
			String[] q_result = DBHelp_JDBC_MySQL.query(tabName, q_fields, q_data, q_fields);
			if (q_result == null) {
				sources.getBookSource().remove(source);
				continue;
			}
			if (q_result.length == 1 && q_result[0] == null) {
				// BaseTools.log("新增书籍来源："+book.getTitle());
				String[] data = { source.get_id(), source.getLastChapter(), source.getLink(), source.getSource(),source.getName(),
						String.valueOf(source.getIsCharge()), String.valueOf(source.getChaptersCount()),
						String.valueOf(source.getStarting()), source.getHost(), bookId, String.valueOf(_type),
						strNowTime };
				DBHelp_JDBC_MySQL.insert(tabName, tab_fields, data,bookName+" : "+source.getLastChapter());
				//更新书籍信息
				//DBHelp_JDBC_MySQL.update("tbl_book",new String[]{"lastChapter","updated"},new String[]{source.getLastChapter(),strNowTime},new String[]{"id"},new String[]{bookId},bookName+":"+source.getLastChapter()+"【最新章节】");
				
			} else {
				// BaseTools.log("更新书籍来源："+book.getTitle());
				String[] u_data = { source.getLastChapter(), source.getLink(), source.getSource(),source.getName(),
						String.valueOf(source.getIsCharge()), String.valueOf(source.getChaptersCount()),
						String.valueOf(source.getStarting()), source.getHost(), bookId, String.valueOf(_type),
						strNowTime };
				DBHelp_JDBC_MySQL.update(tabName, u_fields, u_data, q_fields, q_data,bookName+" : "+source.getLastChapter());
				//更新书籍信息
				//DBHelp_JDBC_MySQL.update("tbl_book",new String[]{"lastChapter","updated"},new String[]{source.getLastChapter(),strNowTime},new String[]{"id"},new String[]{bookId},bookName+":"+source.getLastChapter()+"【最新章节】");
				
			}

			sources.getBookSource().remove(source);
		}
	}
	
	/**
	 * 调用接口获取书籍来源信息
	 * @param _bookId 远程Id
	 * @return 书籍来源json字符串
	 * @author Anson
	 */
	private static String toc(String _bookId) {
		String strJSON = "";
		for (int i = 1; i < 4; i++) {
			setType(i);
			try {
				strJSON=JSONUtil.toc(_bookId, i, "http://api.zhuishushenqi.com/%s?view=summary&book=%s");
				if(!JSONUtil.checkJson(strJSON, Chapter_List.class))
					break;
			} catch (Exception e) {
					return "";
			}
		}
		return "{\"booksource\":" + strJSON + "}";
	}
}
